package io.yunho.jddns.service.impl;

import cn.hutool.cache.Cache;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.yunho.jddns.component.JDDnsProperties;
import io.yunho.jddns.constant.CommonConstant;
import io.yunho.jddns.service.DdnsService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author: Jason
 * @date: 2021/1/21 19:30
 * @description:
 */
@Slf4j
@Service
@AllArgsConstructor
public class DdnsServiceImpl implements DdnsService {
    @Resource
    public final Cache cache;
    @Override
    public void getDdnsIp(JDDnsProperties jdDnsProperties) {
        Assert.notNull(jdDnsProperties,"未配置动态dns参数");
        String result = HttpRequest.get(jdDnsProperties.getGetDomainRecordUrl())
                .header(Header.ACCEPT, "application/json")
                .header(Header.AUTHORIZATION, "sso-key " + jdDnsProperties.getApiKey() + ":" + jdDnsProperties.getApiSecret())
                .setConnectionTimeout(CommonConstant.CONN_TIMEOUT)
                .setReadTimeout(CommonConstant.READ_TIMEOUT)
                .execute().body();
        if(!StrUtil.isBlank(result)){
            String ip = String.valueOf(cache.get(CommonConstant.DDNS_IP));
            JSONArray jsonArray = JSONUtil.parseArray(result);
            JSONObject jsonObject = jsonArray.getJSONObject(0);
            if(jsonObject.get("data")!=null
                    && jsonObject.get("data").equals(ip)){
                log.info("A记录与服务器IP一致，不需要重新解析");
                return;
            }
            log.info("***A记录与服务器IP不一致，需要重新解析，开始更新***");
            putDdnsIp(jdDnsProperties,ip);
            log.info("***A记录与服务器IP不一致，需要重新解析，更新结束***");
            return;
        }
        log.warn("获取域名A记录失败");
    }

    @Override
    public void putDdnsIp(JDDnsProperties jdDnsProperties,String ip) {
        String json = "[ { \"data\": \""+ip+"\", \"port\": 80, \"priority\": 0, \"protocol\": \"string\", \"service\": \"string\", \"ttl\": 600, \"weight\": 0 }]";
        HttpResponse execute = HttpRequest.put(jdDnsProperties.getPutDomainRecordUrl())
                .header(Header.ACCEPT, "application/json")
                .header(Header.CONTENT_TYPE, "application/json")
                .header(Header.AUTHORIZATION, "sso-key " + jdDnsProperties.getApiKey() + ":" + jdDnsProperties.getApiSecret())
                .setConnectionTimeout(CommonConstant.CONN_TIMEOUT)
                .setReadTimeout(CommonConstant.READ_TIMEOUT)
                .body(json).execute();
        if(execute.isOk()) {
            log.info("A记录已重新解析到新的IP：{}", ip);
            return;
        }
        log.warn("A记录重新解析失败，异常情况：{}",execute.body());
    }

    @Override
    public void confirmIp(JDDnsProperties jdDnsProperties) {
        Assert.notNull(jdDnsProperties,"未配置动态dns参数");
        String result = HttpRequest.get(jdDnsProperties.getConfirmIpUrl())
                .setConnectionTimeout(CommonConstant.CONN_TIMEOUT)
                .setReadTimeout(CommonConstant.READ_TIMEOUT)
                .execute().body();
        if(!StrUtil.isBlank(result)){
            JSONObject jsonObject = JSONUtil.parseObj(result);
            if(jsonObject.get("ip")!=null
                    && !StrUtil.isBlank(jsonObject.get("ip").toString())){
                log.info("当前服务器IP：{}",jsonObject.get("ip"));
                cache.put(CommonConstant.DDNS_IP,jsonObject.get("ip"));
                return;
            }
        }
        log.warn("解析当前服务器IP失败");
    }
}
